package com.jarvis.hospital.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.io.Closeable;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by jarvis.liu on 2016-10-25.
 */

public class Util {

    /**
     * Close outputStream
     *
     * @param stream stream
     */
    public static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
                stream = null;
            } catch (IOException e) {
                Log.e("msg", e.getMessage());
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        stream = null;
                        Log.e("msg", e.getMessage());
                    }
                    stream = null;
                }
            }
        }
    }

    /**
     * 网络是否已经连接
     *
     * @param context context
     * @return if is connected
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        return networkinfo != null && networkinfo.isAvailable();
    }

    /**
     * 验证手机格式
     */
    public static boolean match(String pattern, String value) {
        Pattern regex = Pattern.compile(pattern);
        Matcher matcher = regex.matcher(value);
        return matcher.matches();
    }

    /**
     * 安全校验码，生成规则为：
     * Md5(currentTime_salt+手机号后四位.)其中currentTime为上一行的参数,salt为安全盐，具体值请咨询后台，另外注意括号里的符号（_和+和.）
     *
     * @return
     */
    public static String getSecretToken(String time, String phone) {
        String secretToken = "";
        secretToken = time + "_changzheng+" + phone+".";
        System.out.println("secretToken:"+secretToken);
        return MD5.md5WithEncoder(secretToken);
    }
}
